package cn.bellychang.anemicVsdomain;

import cn.bellychang.anemicVsdomain.anemic.Contract;
import cn.bellychang.anemicVsdomain.anemic.RevenueRecognition;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ChangLiang
 * @date 2020/5/18
 */
@Slf4j
public class RecognitionDao {

    /**
     * 模拟数据库
     */
    List<RevenueRecognition> list = new ArrayList<>();

    public Contract findContractById(Long contractId) {
        return Contract.builder().id(1L)
                .productId(10L)
                .revenue(Money.of(CurrencyUnit.of("CNY"), 3000))
                .signedDate(Date.from(Instant.now()))
                .build();
    }

    public ProductNameEnum getProductNameByProductId(Long productId) {
        if (productId.equals(10L)) {
            return ProductNameEnum.SpreadSheet;
        }
        if (productId.equals(11L)) {
            return ProductNameEnum.Word;
        }
        if (productId.equals(12L)) {
            return ProductNameEnum.Database;
        }
        return null;
    }

    public void insertRevenueRecognition(Long contractId, Money money, Date recognitionDate) {
        log.info("contractId: {}, money: {}， recognitionDate: {}", contractId, money.toString(), recognitionDate.toString());
        list.add(RevenueRecognition.builder().contractId(contractId)
                .amount(money)
                .recognizedDate(recognitionDate).build());
    }

    /**
     *
     * @param recognitionDate
     * @param contractId if contractId==null, then calculate all contracts, else do assigned contract
     * @return
     */
    public Money getRecognitionListByDate(Date recognitionDate, Long contractId) {
        List<Money> collect = Objects.isNull(contractId) ?
                list.stream()
                        .filter(r -> r.getRecognizedDate().before(recognitionDate))
                        .map(r -> r.getAmount()).collect(Collectors.toList()) :
                list.stream()
                        .filter(r -> r.getRecognizedDate().before(recognitionDate) && r.getContractId().equals(contractId))
                        .map(r -> r.getAmount()).collect(Collectors.toList());
        return Money.total(collect);
    }
}
